﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using MICZ.CodeBuilder.Commons.ConfigExtensions;
using MICZ.CodeBuilder.Commons.JwtExtensions;
using MICZ.CodeBuilder.IService.Userinfo;
using MICZ.CodeBuilder.Service.Userinfo;
using MICZ.CodeBuilder.ViewModels.WeChat;

namespace MICZ.CodeBuilder.WebApi.Controllers
{
    public class LoginController : BaseController
    {
        IUserinfoService userinfoService;

        public LoginController(IUserinfoService _userinfoService)
        {
            userinfoService = _userinfoService;
        }

        /// <summary>
        /// 微信登录Code
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        //[EnableCors]
        //public IActionResult WXLogin(string code)
        //{
        //    if (string.IsNullOrWhiteSpace(code))
        //    {
        //        JsonDataModel.Status = 0;
        //        JsonDataModel.Msg = "参数为空";
        //        return Json(JsonDataModel);
        //    }
        //    HttpClient httpClient = new HttpClient();
        //    string format = string.Format("appid={0}&secret={1}&js_code="+code+"&grant_type=authorization_code",
        //        ConfigExtensions.GetConfigurationValue("WeChatApi", "Appid"), ConfigExtensions.GetConfigurationValue("WeChatApi", "Secret"));
        //    //{"session_key":"mYr+3xWo5SVpS9daE3xwhw==","openid":"ot7vd4rgRouavbkUVF5hiZUjnFyI"}
        //    var result = httpClient.GetAsync(ConfigExtensions.GetConfigurationValue("WeChatApi", "Api") + "?" + format).Result.Content.ReadAsStringAsync().Result;
        //    WeChatAuthDot weChatAuthDot = JsonConvert.DeserializeObject<WeChatAuthDot>(result);
        //    MICZ.CodeBuilder.Models.Userinfo userinfo =  userinfoService.Get(a => a.USERID == weChatAuthDot.openid);
        //    dynamic obj = new MICZ.CodeBuilder.Commons.DynamicExtensions.DynamicObjectHelper();
        //    if (userinfo == null)
        //    {
        //        MICZ.CodeBuilder.Models.Userinfo _userinfo = new Models.Userinfo();
        //        _userinfo.USERID = weChatAuthDot.openid;
        //        _userinfo.USERNAME = weChatAuthDot.openid;
        //        _userinfo.TYPE = 2;
        //        _userinfo.OPENID = weChatAuthDot.openid;
        //        _userinfo.LOGINTYPE = 0;
        //        _userinfo.ISSTATE = 1;
        //        _userinfo.ISDEL = 0;
        //        _userinfo.CREATEID = 0;
        //        _userinfo.CREATENAME = weChatAuthDot.openid;
        //        _userinfo.CREATEDATETIME = DateTime.Now;
        //        _userinfo.UPDATEID = 0;
        //        _userinfo.UPDATENAME = weChatAuthDot.openid;
        //        _userinfo.UPDATEDATETIME = DateTime.Now;
        //        long cmdid=  userinfoService.Create(_userinfo,a=> new { a.ID});
        //        _userinfo.ID = (Int32)cmdid;
        //        userinfo = _userinfo;
        //    }
        //    var JWT = JwtHelper.CreateJWT(userinfo.USERID, userinfo.ID.ToString());
        //    obj.set("JWT", JWT);
        //    JsonDataModel.Status = 1;
        //    JsonDataModel.Msg = "登录成功";
        //    JsonDataModel.Data = obj;
        //    return Json(JsonDataModel);
        //}

        /// <summary>
        /// 普通登录
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [EnableCors]
        public IActionResult OnLogin(string uid, string pwd)
        {
            MICZ.CodeBuilder.Models.Userinfo userinfo =  userinfoService.Get(a => a.USERID == uid && a.PASSWORD == pwd);
            if (userinfo == null)
            {
                JsonDataModel.Status = 0;
                JsonDataModel.Msg = "登录失败,账户或密码错误";
                return Json(JsonDataModel);
            }
            dynamic obj = new MICZ.CodeBuilder.Commons.DynamicExtensions.DynamicObjectHelper();
            var JWT = JwtHelper.CreateJWT(userinfo.USERID, userinfo.ID.ToString());
            obj.set("JWT", JWT);
            JsonDataModel.Status = 1;
            JsonDataModel.Msg = "登录成功";
            JsonDataModel.Data = obj;
            return Json(JsonDataModel);
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        /// <returns></returns>
        [EnableCors]
        public IActionResult IsLogin()
        {
            // 当api发送请求，自动调用这个方法
            var request = Request.HttpContext.Request; // 获取请求的请求体
            //var authorization = request.Headers.Authorization; // 获取请求的token对象
            //var authorization = HttpContext.GetTokenAsync("access_token"); // 获取请求的token对象
            var authorization = request.Headers["Authorization"]; // 获取请求的token对象
            if (string.IsNullOrWhiteSpace(authorization)) {
                JsonDataModel.Status = 0;
                JsonDataModel.Msg = "登录失败";
                return Json(JsonDataModel);
            }
            //var token1 = JwtHelper.SerializeJWT(authorization);
            dynamic obj = new MICZ.CodeBuilder.Commons.DynamicExtensions.DynamicObjectHelper();
            bool token = JwtHelper.GetPrincipal(authorization);
            obj.set("JWT", token);
            if (token)
            {
                JsonDataModel.Status = 1;
                JsonDataModel.Msg = "登录成功";
                JsonDataModel.Data = obj;
                return Json(JsonDataModel);
            }
            JsonDataModel.Status = 0;
            JsonDataModel.Msg = "登录失败";
            JsonDataModel.Data = obj;
            return Json(JsonDataModel);
        }

        /// <summary>
        /// 未登录提示(未启用)
        /// </summary>
        /// <returns></returns>
        [EnableCors]
        public IActionResult Error()
        {

            return Content("登录超时或未登录");

        }
    }
}
